{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Sentence classification"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In this tutorial we will try to predict whether an SMS is a spam or not. To train our model, we will use the `SMSSpam` dataset. This dataset is unbalanced, there is only 13.4% spam. Let's look at the data:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "SMS Spam Collection dataset.\n",
       "\n",
       "The data contains 5,574 items and 1 feature (i.e. SMS body). Spam messages represent\n",
       "13.4% of the dataset. The goal is to predict whether an SMS is a spam or not.\n",
       "\n",
       "      Name  SMSSpam                                                                              \n",
       "      Task  Binary classification                                                                \n",
       "   Samples  5,574                                                                                \n",
       "  Features  1                                                                                    \n",
       "    Sparse  False                                                                                \n",
       "      Path  /Users/max.halford/river_data/SMSSpam/SMSSpamCollection                              \n",
       "       URL  https://archive.ics.uci.edu/ml/machine-learning-databases/00228/smsspamcollection.zip\n",
       "      Size  466.71 KB                                                                            \n",
       "Downloaded  False                                                                                "
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from river import datasets\n",
    "\n",
    "datasets.SMSSpam()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Downloading https://archive.ics.uci.edu/ml/machine-learning-databases/00228/smsspamcollection.zip (198.65 KB)\n",
      "Uncompressing into /Users/max.halford/river_data/SMSSpam\n",
      "{'body': 'Go until jurong point, crazy.. Available only in bugis n great world '\n",
      "         'la e buffet... Cine there got amore wat...\\n'}\n",
      "Spam: False\n"
     ]
    }
   ],
   "source": [
    "from pprint import pprint\n",
    "\n",
    "X_y = datasets.SMSSpam()\n",
    "\n",
    "for x, y in X_y:\n",
    "    pprint(x)\n",
    "    print(f'Spam: {y}')\n",
    "    break"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's start by building a simple model like a Naive Bayes classifier. We will first preprocess the sentences with a TF-IDF transform that our model can consume. Then, we will measure the accuracy of our model with the AUC metric. This is the right metric to use when the classes are not balanced. In addition, the Naive Bayes models can perform very well on unbalanced datasets and can be used for both binary and multi-class classification problems."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "ROCAUC: 0.929296"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from river import feature_extraction\n",
    "from river import naive_bayes\n",
    "from river import metrics\n",
    "\n",
    "def extract_body(x):\n",
    "    \"\"\"Extract the body of the sms.\"\"\"\n",
    "    return x['body']\n",
    "\n",
    "X_y = datasets.SMSSpam()\n",
    "\n",
    "model = (\n",
    "    extract_body | \n",
    "    feature_extraction.TFIDF() | \n",
    "    naive_bayes.BernoulliNB(alpha=0)\n",
    ")\n",
    "\n",
    "metric = metrics.ROCAUC()\n",
    "cm = metrics.ConfusionMatrix()\n",
    "\n",
    "for x, y in X_y:\n",
    "    \n",
    "    y_pred = model.predict_one(x)\n",
    "    \n",
    "    if y_pred is not None:\n",
    "        metric.update(y_pred=y_pred, y_true=y)\n",
    "        cm.update(y_pred=y_pred, y_true=y)\n",
    "    \n",
    "    model.learn_one(x, y)\n",
    "    \n",
    "metric"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The confusion matrix:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "           False    True\n",
       "   False    4809      17\n",
       "    True     103     644"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "cm"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The results are quite good with this first model."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Since we are working with an unbalanced dataset, we can use the `imblearn` module to rebalance the classes of our dataset. For more information about the `imblearn` module, you can find a dedicated tutorial [here](../imbalanced-learning)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "ROCAUC: 0.951728"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from river import imblearn\n",
    "\n",
    "X_y = datasets.SMSSpam()\n",
    "\n",
    "model = (\n",
    "    extract_body | \n",
    "    feature_extraction.TFIDF() | \n",
    "    imblearn.RandomUnderSampler(\n",
    "        classifier=naive_bayes.BernoulliNB(alpha=0),\n",
    "        desired_dist={0: .5, 1: .5},\n",
    "        seed=42\n",
    "    )\n",
    ")\n",
    "\n",
    "metric = metrics.ROCAUC()\n",
    "cm = metrics.ConfusionMatrix()\n",
    "\n",
    "for x, y in X_y:\n",
    "    \n",
    "    y_pred = model.predict_one(x)\n",
    "    \n",
    "    if y_pred is not None:\n",
    "        metric.update(y_pred=y_pred, y_true=y)\n",
    "        cm.update(y_pred=y_pred, y_true=y)\n",
    "    \n",
    "    model.learn_one(x, y)\n",
    "    \n",
    "metric"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The `imblearn` module improved our results. Not bad! We can visualize the pipeline to understand how the data is processed."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The confusion matrix:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "           False    True\n",
       "   False    4624     201\n",
       "    True      41     706"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "cm"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/svg+xml": [
       "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n",
       "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\"\n",
       " \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n",
       "<!-- Generated by graphviz version 2.44.1 (20200629.0846)\n",
       " -->\n",
       "<!-- Pages: 1 -->\n",
       "<svg width=\"167pt\" height=\"335pt\"\n",
       " viewBox=\"0.00 0.00 167.00 335.00\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\">\n",
       "<g id=\"graph0\" class=\"graph\" transform=\"scale(1 1) rotate(0) translate(4 331)\">\n",
       "<polygon fill=\"white\" stroke=\"transparent\" points=\"-4,4 -4,-331 163,-331 163,4 -4,4\"/>\n",
       "<g id=\"clust1\" class=\"cluster\">\n",
       "<title>cluster_RandomUnderSampler</title>\n",
       "<polygon fill=\"none\" stroke=\"black\" points=\"8,-64 8,-139 151,-139 151,-64 8,-64\"/>\n",
       "<text text-anchor=\"middle\" x=\"79.5\" y=\"-123.8\" font-family=\"Times,serif\" font-size=\"14.00\">RandomUnderSampler</text>\n",
       "</g>\n",
       "<!-- x -->\n",
       "<g id=\"node1\" class=\"node\">\n",
       "<title>x</title>\n",
       "<ellipse fill=\"none\" stroke=\"black\" cx=\"79\" cy=\"-309\" rx=\"27\" ry=\"18\"/>\n",
       "<text text-anchor=\"middle\" x=\"79\" y=\"-305.3\" font-family=\"Times,serif\" font-size=\"14.00\">x</text>\n",
       "</g>\n",
       "<!-- extract_body -->\n",
       "<g id=\"node2\" class=\"node\">\n",
       "<title>extract_body</title>\n",
       "<ellipse fill=\"none\" stroke=\"black\" cx=\"79\" cy=\"-237\" rx=\"56.59\" ry=\"18\"/>\n",
       "<text text-anchor=\"middle\" x=\"79\" y=\"-233.3\" font-family=\"Times,serif\" font-size=\"14.00\">extract_body</text>\n",
       "</g>\n",
       "<!-- x&#45;&gt;extract_body -->\n",
       "<g id=\"edge1\" class=\"edge\">\n",
       "<title>x&#45;&gt;extract_body</title>\n",
       "<path fill=\"none\" stroke=\"black\" d=\"M79,-290.7C79,-282.98 79,-273.71 79,-265.11\"/>\n",
       "<polygon fill=\"black\" stroke=\"black\" points=\"82.5,-265.1 79,-255.1 75.5,-265.1 82.5,-265.1\"/>\n",
       "</g>\n",
       "<!-- TFIDF -->\n",
       "<g id=\"node3\" class=\"node\">\n",
       "<title>TFIDF</title>\n",
       "<ellipse fill=\"none\" stroke=\"black\" cx=\"79\" cy=\"-165\" rx=\"35.19\" ry=\"18\"/>\n",
       "<text text-anchor=\"middle\" x=\"79\" y=\"-161.3\" font-family=\"Times,serif\" font-size=\"14.00\">TFIDF</text>\n",
       "</g>\n",
       "<!-- extract_body&#45;&gt;TFIDF -->\n",
       "<g id=\"edge2\" class=\"edge\">\n",
       "<title>extract_body&#45;&gt;TFIDF</title>\n",
       "<path fill=\"none\" stroke=\"black\" d=\"M79,-218.7C79,-210.98 79,-201.71 79,-193.11\"/>\n",
       "<polygon fill=\"black\" stroke=\"black\" points=\"82.5,-193.1 79,-183.1 75.5,-193.1 82.5,-193.1\"/>\n",
       "</g>\n",
       "<!-- BernoulliNB -->\n",
       "<g id=\"node4\" class=\"node\">\n",
       "<title>BernoulliNB</title>\n",
       "<ellipse fill=\"none\" stroke=\"black\" cx=\"79\" cy=\"-90\" rx=\"55.79\" ry=\"18\"/>\n",
       "<text text-anchor=\"middle\" x=\"79\" y=\"-86.3\" font-family=\"Times,serif\" font-size=\"14.00\">BernoulliNB</text>\n",
       "</g>\n",
       "<!-- TFIDF&#45;&gt;BernoulliNB -->\n",
       "<g id=\"edge3\" class=\"edge\">\n",
       "<title>TFIDF&#45;&gt;BernoulliNB</title>\n",
       "<path fill=\"none\" stroke=\"black\" d=\"M79,-146.7C79,-138.25 79,-127.87 79,-118.37\"/>\n",
       "<polygon fill=\"black\" stroke=\"black\" points=\"82.5,-118.18 79,-108.18 75.5,-118.18 82.5,-118.18\"/>\n",
       "</g>\n",
       "<!-- y -->\n",
       "<g id=\"node5\" class=\"node\">\n",
       "<title>y</title>\n",
       "<ellipse fill=\"none\" stroke=\"black\" cx=\"79\" cy=\"-18\" rx=\"27\" ry=\"18\"/>\n",
       "<text text-anchor=\"middle\" x=\"79\" y=\"-14.3\" font-family=\"Times,serif\" font-size=\"14.00\">y</text>\n",
       "</g>\n",
       "<!-- BernoulliNB&#45;&gt;y -->\n",
       "<g id=\"edge4\" class=\"edge\">\n",
       "<title>BernoulliNB&#45;&gt;y</title>\n",
       "<path fill=\"none\" stroke=\"black\" d=\"M79,-71.7C79,-63.98 79,-54.71 79,-46.11\"/>\n",
       "<polygon fill=\"black\" stroke=\"black\" points=\"82.5,-46.1 79,-36.1 75.5,-46.1 82.5,-46.1\"/>\n",
       "</g>\n",
       "</g>\n",
       "</svg>\n"
      ],
      "text/plain": [
       "<graphviz.dot.Digraph at 0x7f95f4cdde80>"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model.draw()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now let's try to use logistic regression to classify messages. We will use different tips to make my model perform better. As in the previous example, we rebalance the classes of our dataset. The logistics regression will be fed from a TF-IDF."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "ROCAUC: 0.946039"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from river import linear_model\n",
    "from river import optim\n",
    "from river import preprocessing\n",
    "\n",
    "X_y = datasets.SMSSpam()\n",
    "\n",
    "model = (\n",
    "    extract_body | \n",
    "    feature_extraction.TFIDF() | \n",
    "    preprocessing.Normalizer() | \n",
    "    imblearn.RandomUnderSampler(\n",
    "        classifier=linear_model.LogisticRegression(\n",
    "            optimizer=optim.SGD(.9), \n",
    "            loss=optim.losses.Log()\n",
    "        ),\n",
    "        desired_dist={0: .5, 1: .5},\n",
    "        seed=42\n",
    "    )\n",
    ")\n",
    "\n",
    "metric = metrics.ROCAUC()\n",
    "cm = metrics.ConfusionMatrix()\n",
    "\n",
    "for x, y in X_y:\n",
    "    \n",
    "    y_pred = model.predict_one(x)\n",
    "\n",
    "    metric.update(y_pred=y_pred, y_true=y)\n",
    "    cm.update(y_pred=y_pred, y_true=y)\n",
    "    \n",
    "    model.learn_one(x, y)\n",
    "    \n",
    "metric"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The confusion matrix:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "           False    True\n",
       "   False    4655     172\n",
       "    True      54     693"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "cm"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/svg+xml": [
       "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n",
       "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\"\n",
       " \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n",
       "<!-- Generated by graphviz version 2.44.1 (20200629.0846)\n",
       " -->\n",
       "<!-- Pages: 1 -->\n",
       "<svg width=\"198pt\" height=\"407pt\"\n",
       " viewBox=\"0.00 0.00 198.00 407.00\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\">\n",
       "<g id=\"graph0\" class=\"graph\" transform=\"scale(1 1) rotate(0) translate(4 403)\">\n",
       "<polygon fill=\"white\" stroke=\"transparent\" points=\"-4,4 -4,-403 194,-403 194,4 -4,4\"/>\n",
       "<g id=\"clust1\" class=\"cluster\">\n",
       "<title>cluster_RandomUnderSampler</title>\n",
       "<polygon fill=\"none\" stroke=\"black\" points=\"8,-64 8,-139 182,-139 182,-64 8,-64\"/>\n",
       "<text text-anchor=\"middle\" x=\"95\" y=\"-123.8\" font-family=\"Times,serif\" font-size=\"14.00\">RandomUnderSampler</text>\n",
       "</g>\n",
       "<!-- x -->\n",
       "<g id=\"node1\" class=\"node\">\n",
       "<title>x</title>\n",
       "<ellipse fill=\"none\" stroke=\"black\" cx=\"95\" cy=\"-381\" rx=\"27\" ry=\"18\"/>\n",
       "<text text-anchor=\"middle\" x=\"95\" y=\"-377.3\" font-family=\"Times,serif\" font-size=\"14.00\">x</text>\n",
       "</g>\n",
       "<!-- extract_body -->\n",
       "<g id=\"node2\" class=\"node\">\n",
       "<title>extract_body</title>\n",
       "<ellipse fill=\"none\" stroke=\"black\" cx=\"95\" cy=\"-309\" rx=\"56.59\" ry=\"18\"/>\n",
       "<text text-anchor=\"middle\" x=\"95\" y=\"-305.3\" font-family=\"Times,serif\" font-size=\"14.00\">extract_body</text>\n",
       "</g>\n",
       "<!-- x&#45;&gt;extract_body -->\n",
       "<g id=\"edge1\" class=\"edge\">\n",
       "<title>x&#45;&gt;extract_body</title>\n",
       "<path fill=\"none\" stroke=\"black\" d=\"M95,-362.7C95,-354.98 95,-345.71 95,-337.11\"/>\n",
       "<polygon fill=\"black\" stroke=\"black\" points=\"98.5,-337.1 95,-327.1 91.5,-337.1 98.5,-337.1\"/>\n",
       "</g>\n",
       "<!-- TFIDF -->\n",
       "<g id=\"node3\" class=\"node\">\n",
       "<title>TFIDF</title>\n",
       "<ellipse fill=\"none\" stroke=\"black\" cx=\"95\" cy=\"-237\" rx=\"35.19\" ry=\"18\"/>\n",
       "<text text-anchor=\"middle\" x=\"95\" y=\"-233.3\" font-family=\"Times,serif\" font-size=\"14.00\">TFIDF</text>\n",
       "</g>\n",
       "<!-- extract_body&#45;&gt;TFIDF -->\n",
       "<g id=\"edge2\" class=\"edge\">\n",
       "<title>extract_body&#45;&gt;TFIDF</title>\n",
       "<path fill=\"none\" stroke=\"black\" d=\"M95,-290.7C95,-282.98 95,-273.71 95,-265.11\"/>\n",
       "<polygon fill=\"black\" stroke=\"black\" points=\"98.5,-265.1 95,-255.1 91.5,-265.1 98.5,-265.1\"/>\n",
       "</g>\n",
       "<!-- Normalizer -->\n",
       "<g id=\"node4\" class=\"node\">\n",
       "<title>Normalizer</title>\n",
       "<ellipse fill=\"none\" stroke=\"black\" cx=\"95\" cy=\"-165\" rx=\"51.19\" ry=\"18\"/>\n",
       "<text text-anchor=\"middle\" x=\"95\" y=\"-161.3\" font-family=\"Times,serif\" font-size=\"14.00\">Normalizer</text>\n",
       "</g>\n",
       "<!-- TFIDF&#45;&gt;Normalizer -->\n",
       "<g id=\"edge4\" class=\"edge\">\n",
       "<title>TFIDF&#45;&gt;Normalizer</title>\n",
       "<path fill=\"none\" stroke=\"black\" d=\"M95,-218.7C95,-210.98 95,-201.71 95,-193.11\"/>\n",
       "<polygon fill=\"black\" stroke=\"black\" points=\"98.5,-193.1 95,-183.1 91.5,-193.1 98.5,-193.1\"/>\n",
       "</g>\n",
       "<!-- LogisticRegression -->\n",
       "<g id=\"node5\" class=\"node\">\n",
       "<title>LogisticRegression</title>\n",
       "<ellipse fill=\"none\" stroke=\"black\" cx=\"95\" cy=\"-90\" rx=\"78.79\" ry=\"18\"/>\n",
       "<text text-anchor=\"middle\" x=\"95\" y=\"-86.3\" font-family=\"Times,serif\" font-size=\"14.00\">LogisticRegression</text>\n",
       "</g>\n",
       "<!-- Normalizer&#45;&gt;LogisticRegression -->\n",
       "<g id=\"edge3\" class=\"edge\">\n",
       "<title>Normalizer&#45;&gt;LogisticRegression</title>\n",
       "<path fill=\"none\" stroke=\"black\" d=\"M95,-146.7C95,-138.25 95,-127.87 95,-118.37\"/>\n",
       "<polygon fill=\"black\" stroke=\"black\" points=\"98.5,-118.18 95,-108.18 91.5,-118.18 98.5,-118.18\"/>\n",
       "</g>\n",
       "<!-- y -->\n",
       "<g id=\"node6\" class=\"node\">\n",
       "<title>y</title>\n",
       "<ellipse fill=\"none\" stroke=\"black\" cx=\"95\" cy=\"-18\" rx=\"27\" ry=\"18\"/>\n",
       "<text text-anchor=\"middle\" x=\"95\" y=\"-14.3\" font-family=\"Times,serif\" font-size=\"14.00\">y</text>\n",
       "</g>\n",
       "<!-- LogisticRegression&#45;&gt;y -->\n",
       "<g id=\"edge5\" class=\"edge\">\n",
       "<title>LogisticRegression&#45;&gt;y</title>\n",
       "<path fill=\"none\" stroke=\"black\" d=\"M95,-71.7C95,-63.98 95,-54.71 95,-46.11\"/>\n",
       "<polygon fill=\"black\" stroke=\"black\" points=\"98.5,-46.1 95,-36.1 91.5,-46.1 98.5,-46.1\"/>\n",
       "</g>\n",
       "</g>\n",
       "</svg>\n"
      ],
      "text/plain": [
       "<graphviz.dot.Digraph at 0x7f95f4cb7f10>"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model.draw()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The results of the logistic regression are quite good but still inferior to the naive Bayes model."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's try to use word embeddings to improve our logistic regression. Word embeddings allow you to represent a word as a vector. Embeddings are developed to build semantically rich vectors. For instance, the vector which represents the word **python** should be close to the vector which represents the word **programming**. We will use [spaCy](https://spacy.io/) to convert our sentence to vectors. spaCy converts a sentence to a vector by calculating the average of the embeddings of the words in the sentence."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can download pre-trained embeddings in many languages. We will use English pre-trained embeddings as our SMS are in English."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The command below allows you to download the pre-trained embeddings that spaCy makes available. More informations about spaCy and its installation may be found here [here](https://spacy.io/usage)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```sh\n",
    "python -m spacy download en_core_web_sm\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here, we create a custom transformer to convert an input sentence to a dict of floats. We will integrate this transformer into our pipeline."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "ename": "ModuleNotFoundError",
     "evalue": "No module named 'spacy'",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mModuleNotFoundError\u001b[0m                       Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-11-f2a8877fc890>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0;32mimport\u001b[0m \u001b[0mspacy\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m      2\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m      3\u001b[0m \u001b[0;32mfrom\u001b[0m \u001b[0mriver\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mbase\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mTransformer\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m      4\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m      5\u001b[0m \u001b[0;32mclass\u001b[0m \u001b[0mEmbeddings\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mTransformer\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;31mModuleNotFoundError\u001b[0m: No module named 'spacy'"
     ]
    }
   ],
   "source": [
    "import spacy\n",
    "\n",
    "from river.base import Transformer\n",
    "\n",
    "class Embeddings(Transformer):\n",
    "    \"\"\"My custom transformer, word embedding using spaCy.\"\"\"\n",
    "    \n",
    "    def __init__(self):\n",
    "        self.embeddings = spacy.load('en_core_web_sm')\n",
    "        \n",
    "    def transform_one(self, x, y=None):\n",
    "        return {dimension: xi for dimension, xi in enumerate(self.embeddings(x).vector)}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's train our logistic regression:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "X_y = datasets.SMSSpam()\n",
    "\n",
    "model = (\n",
    "    extract_body | \n",
    "    Embeddings() | \n",
    "    preprocessing.Normalizer() |\n",
    "    imblearn.RandomOverSampler(\n",
    "        classifier=linear_model.LogisticRegression(\n",
    "            optimizer=optim.SGD(.5), \n",
    "            loss=optim.losses.Log()\n",
    "        ),\n",
    "        desired_dist={0: .5, 1: .5},\n",
    "        seed=42\n",
    "    )\n",
    ")\n",
    "\n",
    "metric = metrics.ROCAUC()\n",
    "cm = metrics.ConfusionMatrix()\n",
    "\n",
    "for x, y in X_y:\n",
    "    \n",
    "    y_pred = model.predict_one(x)\n",
    "    \n",
    "    metric.update(y_pred=y_pred, y_true=y)\n",
    "    cm.update(y_pred=y_pred, y_true=y)\n",
    "    \n",
    "    model.learn_one(x, y)\n",
    "\n",
    "metric"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The confusion matrix:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "cm"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "model"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The results of the logistic regression using spaCy embeddings are lower than those obtained with TF-IDF values. We could surely improve the results by cleaning up the text. We could also use embeddings more suited to our dataset. However, on this problem, the logistic regression is not better than the Naive Bayes model. No free lunch today."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
